package net.lab1024.sa.admin.module.system.sms;

import net.lab1024.sa.base.common.domain.ResponseDTO;
import net.lab1024.sa.base.module.support.redis.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class SmsCodeServiceImpl implements SmsCodeService {
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private RedisService redisService;

    @Value("${sms.code.length:6}")
    private int codeLength;

    @Value("${sms.code.expire:300}") // 5分钟（秒）
    private long expireSeconds;

    @Override
    public String generateCode() {
        // 生成随机数字验证码
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < codeLength; i++) {
            code.append(random.nextInt(10));
        }

        return code.toString();
    }

    @Override
    public void saveCodeToRedis(String mobile, String code) {
        String key = "sms:code:" + mobile;
        System.out.println("saveCodeToRedis key=" + key + ", code=" + code);
        code = "123456";
        redisService.set(key, code, expireSeconds);
    }

    @Override
    public ResponseDTO<String> verifyCode(String mobile, String inputCode) {
        String key = "sms:code:" + mobile;
        String storedCode = redisService.get(key);
        if (storedCode == null) {
            return ResponseDTO.userErrorParam("验证码错误");
        }
        // 校验后删除验证码（一次性）
        redisService.delete(key);
        if (!storedCode.equals(inputCode)) {
            return ResponseDTO.userErrorParam("验证码错误");
        }else {
            return ResponseDTO.ok();
        }
    }
//    @Override
//    public boolean checkSendFrequency(String mobile) {
//        // 限制：每分钟最多发送1次，每小时最多5次
//        String minuteKey = "sms:freq:minute:" + mobile;
//        String hourKey = "sms:freq:hour:" + mobile;
//        long minuteCount = redisTemplate.opsForValue().increment(minuteKey, 1, 60, TimeUnit.SECONDS);
//        if (minuteCount > 1) {
//            return true; // 每分钟超过1次
//        }
//        long hourCount = redisTemplate.opsForValue().increment(hourKey, 1, 3600, TimeUnit.SECONDS);
//        return hourCount > 5; // 每小时超过5次
//    }

}
